package com.leorui.schoollife.controller.impl

import com.leorui.schoollife.controller.IUserControl
import com.leorui.schoollife.entity.*
import com.leorui.schoollife.entity.response.CommonResponse
import com.leorui.schoollife.mapper.IDBFriendCircle
import com.leorui.schoollife.mapper.IDBIcons
import com.leorui.schoollife.mapper.IDBUser
import com.leorui.schoollife.utils.OkHttpUtils
import com.leorui.schoollife.utils.SchoolParseUtils
import com.mysql.cj.util.Base64Decoder
import org.apache.logging.log4j.util.Base64Util
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.util.Base64Utils
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder
import java.util.*

@Controller
class UserControllerImpl : IUserControl {
    @Autowired(required = false)
    var dbUser: IDBUser? = null

    @Autowired(required = false)
    var dbIcons: IDBIcons? = null

    @Autowired(required = false)
    var dbFriendCircle: IDBFriendCircle? = null

    // 用户登录
    @ResponseBody
    @PostMapping("/api/v1/user_login")
    override fun login(
            @RequestParam(name = "account") account: String,
            @RequestParam(name = "password", required = false) password: String
    ): Map<Any?, Any?> {
        if (account.isEmpty()) {
            return CommonResponse(1, "account is empty", false).toMap()
        }
        if (password.isEmpty()) {
            return CommonResponse(1, "password is empty", false).toMap()
        }
        val saveCount = dbUser?.checkAccountAndPassword(account, password)
                ?: return CommonResponse(1, "userMapper error, is null", false).toMap()
        if (saveCount > 0) {
            // 只有有用户才能成功登录
            return CommonResponse(0, null, true).toMap()
        }
        return CommonResponse(0, null, false).toMap()
    }

    // 创建用户
    @ResponseBody
    @PostMapping("/api/v1/create_user")
    override fun createNewUser(
            @RequestParam("account", required = true) account: String,
            @RequestParam("password", required = true) password: String
    ): Map<Any?, Any?> {
        if (account.isEmpty()) {
            return CommonResponse(1, "account is empty", false).toMap()
        }
        if (password.isEmpty()) {
            return CommonResponse(1, "password is empty", false).toMap()
        }
        dbUser?.addStudentAccount(account, password)
                ?: return CommonResponse(1, "userMapper error, is null", false).toMap()
        return CommonResponse(0, null, true).toMap()
    }

    // 注销用户
    @ResponseBody
    @PostMapping("/api/v1/delete_user")
    override fun deleteCurrentUser(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "password", required = true) password: String
    ): Map<Any?, Any?> {
        try {
            val result = dbUser?.changeUserPassword(account, password)
            if (result == null || result == 0) {
                return CommonResponse(1, "请重新确认账号以及密码", false).toMap()
            }
            val friendCircleList = dbFriendCircle?.selectAllFriendCircleListByAccount(account, 1000, 0)
            friendCircleList?.forEach { friendCircleMessage ->
                friendCircleMessage.conversationId?.let { conversationId ->
                    val commitList = dbFriendCircle?.selectConversationCommit(conversationId)
                    // 删除评论
                    commitList?.forEach { commitItem ->
                        commitItem?.commitId?.let {
                            dbFriendCircle?.deleteCommit(it)
                        }
                    }
                    dbFriendCircle?.deleteAllCommitConversation(conversationId)

                }
            }
            dbFriendCircle?.deleteAllAgree(account)
            dbFriendCircle?.deleteAllConversation(account)
            return CommonResponse(0, null, true).toMap()
        } catch (e: Exception) {
            return CommonResponse(1, e.message, false).toMap()
        }
    }

    // 判断用户是否存在
    @ResponseBody
    @PostMapping("/api/v1/query_user_exists")
    override fun checkCurrentUserIsSave(
            @RequestParam("account", required = true) account: String
    ): Map<Any?, Any?> {
        if (account.isEmpty()) {
            return CommonResponse(1, "account is empty", false).toMap()
        }
        val count = dbUser?.queryAccountIsSave(account)
                ?: return CommonResponse(1, "userMapper error, is null", true).toMap()
        if (count > 0) {
            return CommonResponse(0, null, true).toMap()
        }
        return CommonResponse(0, null, false).toMap()
    }

    // 获取用户权限
    @ResponseBody
    @PostMapping("/api/v1/get_person_power")
    override fun getCurrentUserPower(@RequestParam(name = "account", required = true) account: String): Map<Any?, Any?> {
        val power = dbUser?.selectAccountPower(account)
                ?: return CommonResponse(1, "userMapper error, is null", true).toMap()
        return CommonResponse(0, null, true, power).toMap()
    }

    // 检查密码是否正确
    @ResponseBody
    @PostMapping("/api/v1/check_user_password")
    override fun checkCurrentUserPassword(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "password", required = true) password: String
    ): Map<Any?, Any?> {
        val count: Int
        try {
            count = dbUser?.checkAccountAndPassword(account, password)
                    ?: return CommonResponse(1, "数据库问题", false).toMap()
        } catch (e: Exception) {
            return CommonResponse(1, e.message, false).toMap()
        }
        return if (count == 0) {
            CommonResponse(0, null, false).toMap()
        } else {
            CommonResponse(0, null, true).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/change_password")
    override fun changeCurrentUserPassword(
            @RequestParam(name = "account") account: String,
            @RequestParam(name = "password") newPassword: String
    ): Map<Any?, Any?> {
        try {
            dbUser?.changeUserPassword(account, newPassword)
                    ?: return CommonResponse(1, "数据库问题", false).toMap()
        } catch (e: Exception) {
            return CommonResponse(1, e.message, false).toMap()
        }
        return CommonResponse(0, null, true).toMap()
    }

    @ResponseBody
    @PostMapping("/api/v1/pull_icons_list")
    override fun getIconsList(): Map<Any?, Any?> {
        return try {
            val iconList = dbIcons?.selectPhotoList() ?: return PhotoEntityResponse(1, "数据库问题").toMap()
            PhotoEntityResponse(0, null, iconList).toMap()
        } catch (e: Exception) {
            PhotoEntityResponse(1, e.message).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/select_user_school")
    override fun getUserSchoolHomePage(
            @RequestParam(name = "account") account: String
    ): Map<Any?, Any?> {
        return try {
            val userSchool = dbUser?.selectUserSchool(account)
            UserSchoolResponse(0, null, userSchool).toMap()
        } catch (e: Exception) {
            UserSchoolResponse(1, e.message, null).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/select_all_school")
    override fun getSchoolList(): Map<Any?, Any?> {
        return try {
            val schoolList = dbUser?.selectAllSchool()
            SchoolResponse(0, null, schoolList).toMap()
        } catch (e: Exception) {
            SchoolResponse(1, e.message, null).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/change_school")
    override fun changeSchool(
            @RequestParam(name = "account") account: String,
            @RequestParam(name = "school_id") schoolId: Int
    ): Map<Any?, Any?> {
        return try {
            dbUser?.changeUserSchool(schoolId, account)
            CommonResponse(0, null, true).toMap()
        } catch (e: Exception) {
            CommonResponse(1, e.message, false).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/pull_user_memorandum_list")
    override fun pullUserMemorandumList(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "page_size", required = false) pageSize: Int?,
            @RequestParam(name = "current_page", required = false) currentPage: Int?
    ): Map<Any?, Any?> {
        return try {
            val defaultPageSize: Int = pageSize ?: 10
            val defaultCurrentPage: Int = currentPage ?: 1

            val noteList = dbUser?.pullUserMemorandumList(account, defaultPageSize, (defaultCurrentPage - 1) * defaultPageSize)
            val countNum = dbUser?.countUserAllMemorandum(account) ?: 0
            ListNoteResponse(0, null, defaultPageSize, defaultCurrentPage, defaultCurrentPage * defaultPageSize < countNum, noteList).toMap()
        } catch (e: Exception) {
            ListNoteResponse(1, e.message).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/update_user_memorandum")
    override fun updateUserMemorandum(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "note_id", required = true) note_id: String,
            @RequestParam(name = "title", required = true) title: String,
            @RequestParam(name = "msg", required = true) msg: String,
            @RequestParam(name = "last_edit_time", required = true) last_edit_time: String
    ): Map<Any?, Any?> {
        return try {
            dbUser?.updateUserMemorandum(account, note_id, title, msg, last_edit_time)
            CommonResponse(0, null, true).toMap()
        } catch (e: Exception) {
            CommonResponse(1, e.message, false).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/delete_user_memorandum")
    override fun deleteUserMemorandum(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "note_id", required = true) note_id: String
    ): Map<Any?, Any?> {
        return try {
            dbUser?.deleteUserMemorandum(account, note_id)
            CommonResponse(0, null, true).toMap()
        } catch (e: Exception) {
            CommonResponse(1, e.message, false).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/add_user_memorandum")
    override fun addUserMemorandum(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "note_id", required = true) note_id: String,
            @RequestParam(name = "title", required = true) title: String,
            @RequestParam(name = "msg", required = true) msg: String,
            @RequestParam(name = "record_start_time", required = true) record_start_time: String,
            @RequestParam(name = "last_edit_time", required = true) last_edit_time: String
    ): Map<Any?, Any?> {
        return try {
            dbUser?.addUserMemorandum(account, note_id, title, msg, record_start_time, last_edit_time)
            CommonResponse(0, null, true).toMap()
        } catch (e: Exception) {
            CommonResponse(1, e.message, false).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/pull_user_memorandum")
    override fun pullUserMemorandum(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "note_id", required = true) note_id: String
    ): Map<Any?, Any?> {
        return try {
            val note = dbUser?.selectUserMemorandum(account, note_id)
            SingleNoteResponse(0, null, note).toMap()
        } catch (e: Exception) {
            SingleNoteResponse(1, e.message, null).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/delete_user_memorandum_list")
    override fun deleteUserMemorandumList(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "note_id_list", required = true) note_id_list: List<String?>
    ): Map<Any?, Any?> {

        return try {
            note_id_list.forEach {
                dbUser?.deleteUserMemorandum(account, it ?: "")
            }
            CommonResponse(0, null, true).toMap()
        } catch (e: Exception) {
            CommonResponse(1, e.message, false).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/pull_user_school_announcement")
    override fun pullUserSchoolAnnouncement(
            @RequestParam(name = "account", required = true) account: String
    ): Map<Any?, Any?> {
        // 查询当前用户的学校信息，以及学校所对应的官网信息，解析的类型
        val schoolInfo = dbUser?.selectUserSchool(account)
        return if (schoolInfo?.schoolWebUrl?.isNotEmpty() == true) {
            var errorMessage: String? = null
            var list: List<SchoolAnnouncementEntity?>? = null
            val okHttpUtils = OkHttpUtils()
            okHttpUtils.init()
            okHttpUtils.callback = object : OkHttpUtils.IntelCallback {
                override fun onError(msg: String?) {
                    errorMessage = msg
                }

                override fun onResponse(html: String?) {
                    list = SchoolParseUtils.parseHomePage(schoolInfo.parseType ?: 0, html
                            ?: "", schoolInfo.schoolWebUrl!!)
                }
            }
            okHttpUtils.postExecute(schoolInfo.schoolWebUrl!!) // 同步调用
            if (errorMessage == null) {
                SchoolAnnouncementResponse(0, null, list).toMap()
            } else {
                SchoolAnnouncementResponse(1, errorMessage, null).toMap()
            }
        } else {
            SchoolAnnouncementResponse(1, "数据库错误，无学校信息", null).toMap()
        }
    }

    @ResponseBody
    @PostMapping("/api/v1/pull_detail_news_web_url")
    override fun pullUserSchoolAnnouncementDetail(
            @RequestParam(name = "account", required = true) account: String,
            @RequestParam(name = "base64_url", required = true) base64Url: String
    ): Map<Any?, Any?> {
        val schoolInfo = dbUser?.selectUserSchool(account)
        return if (schoolInfo?.schoolWebUrl?.isNotEmpty() == true) {
            var errorMessage: String? = null
            var detailEntity: SchoolAnnouncementDetailEntity? = null
            val okHttpUtils = OkHttpUtils()
            okHttpUtils.init()
            okHttpUtils.callback = object : OkHttpUtils.IntelCallback {
                override fun onError(msg: String?) {
                    errorMessage = msg
                }

                override fun onResponse(html: String?) {
                    detailEntity = SchoolParseUtils.parseDetailPage(schoolInfo.parseType ?: 0, html
                            ?: "", schoolInfo.schoolWebUrl!!)
                }
            }


            val decodeByteArray = Base64.getMimeDecoder().decode(base64Url)

            okHttpUtils.postExecute(String(decodeByteArray)) // 同步调用
            if (errorMessage == null) {
                SchoolAnnouncementDetailResponse(0, null, detailEntity).toMap()
            } else {
                SchoolAnnouncementDetailResponse(1, errorMessage, null).toMap()
            }
        } else {
            SchoolAnnouncementDetailResponse(1, "数据库错误，无学校信息", null).toMap()
        }
    }
}